# coding=utf-8
import requests
from log import logger
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# 忽略 SSL 证书验证
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class RedFishService(object):
    prefix = 'https://'
    get_token_url = '/redfish/v1/SessionService/Sessions'   # 获取token
    get_bios_version_url = '/redfish/v1/UpdateService/FirmwareInventory/Bios'   # 获取bios版本
    get_nic_list_message_url = '/redfish/v1/Chassis/1/NetworkAdapters'  # 获取网卡集合资源信息
    get_cpu_list_message_url = '/redfish/v1/Systems/1/Processors'  # 获取cpu集合资源信息
    get_memory_list_message_url = '/redfish/v1/Systems/1/Memory'  # 获取内存集合资源信息
    get_pdisk_list_message_url = '/redfish/v1/Chassis/1/Drives'  # 获取物理盘列表
    get_raid_list_message_url = '/redfish/v1/Systems/1/Storages'  # 获取raid卡列表

    def __init__(self, data):
        self.password = data.get('password')
        self.user_name = data.get('username')
        self.host = data.get('ip')

    def get_token(self):
        """
        获取token
        :return:
        """
        host = self.host
        user_name = self.user_name
        password = self.password
        complete_url = self.prefix + host + self.get_token_url
        data = {'UserName': user_name, 'Password': password}
        rsp = requests.post(complete_url, json=data, verify=False)
        if not str(rsp.status_code).startswith('2'):
            logger.info(
                'redfish http error. url: %s, data: %s, status_code: %s' % (complete_url, data, rsp.status_code))
            return rsp
        token = rsp.headers.get('X-Auth-Token')
        return token

    def http(self, method, url, data, headers=None):
        """
        远程调用
        :param headers: 请求头
        :param method: 请求方法
        :param url: 请求路径
        :param data: 请求参数
        :return:
        """
        token = self.get_token()
        host = self.host
        if headers is None:
            headers = {}
        # 此做法是防止headers中有其他的值传入 如 If-Match
        headers.update({'X-Auth-Token': token})
        complete_url = url.format(host_ip=host)
        if type(token) != str:
            return token, complete_url
        logger.info('redfish http body: %s, url: %s, method is: %s' % (data, complete_url, method))
        if method.upper() == 'GET':
            rsp = requests.get(url=complete_url, headers=headers, verify=False)
        elif method.upper() == 'PATCH':
            rsp = requests.patch(url=complete_url, json=data, headers=headers, verify=False)
        else:
            rsp = requests.post(url=complete_url, json=data, headers=headers, verify=False)
        logger.debug('redfish http rsp. url: %s, data: %s, status_code: %s, content: %s' %
                     (complete_url, data, rsp.status_code, rsp.content))
        # 不同版本的redfish路由略有区别
        if rsp.status_code == 404 and '/1/' in complete_url:
            url = complete_url.replace('/1/', '/Self/')
            rsp = self.http('GET', url, data=data)
        elif int(rsp.status_code) >= 300:
            logger.info('redfish http error. url: %s, data: %s, status_code: %s, content: %s' %
                        (complete_url, data, rsp.status_code, rsp.content))
            return rsp, complete_url
        return rsp[0] if type(rsp) == tuple else rsp, complete_url
